<template>
  <div class="customerAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <!-- v-if="!contactAddShow" 保存不隐藏 -->
    <div class="search-button">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave(customerFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        v-show="!contactAddShow"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title"
            >{{
              pageType !== "detail"
                ? pageType === "add"
                  ? "新增"
                  : "编辑"
                : ""
            }}飞行数据</span
          >
        </template>
        <div class="customer-info">
          <el-form
            :model="customerForm"
            ref="customerFormRef"
            :rules="queryRules"
            label-width="100px"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="飞行类型：" prop="flyType">
                  <el-select
                    ref="refSelect"
                    v-model="customerForm.flyType"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in flightTypeList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="单位地址:" prop="cityId">
                  <el-select
                    filterable
                    style="width: 90px"
                    v-model="customerForm.provinceId"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                    @change="handleProvince('province')"
                  >
                    <el-option
                      v-for="dict in provinceList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <el-select
                    filterable
                    style="width: 90px; margin: 0 5px"
                    v-model="customerForm.cityId"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                    @change="handleProvince('city')"
                  >
                    <el-option
                      v-for="dict in cityList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <el-select
                    filterable
                    style="width: 90px"
                    v-model="customerForm.zoneId"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in areaList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="选择项目：">
                  <el-select
                    v-model="customerForm.projectId"
                    style="width: 268px"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <!-- @change="handleprojectIdschange" -->
                    <el-option key="0" label="" value="" disabled>
                      <span style="float: left; color: #8492a6">项目编号</span>
                      <span style="margin: 0 80px 0 100px; color: #8492a6"
                        >项目名称</span
                      >
                      <span
                        style="
                          margin: 0 50px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >项目类别</span
                      >
                      <span style="color: #8492a6; font-size: 13px"
                        >项目类型</span
                      >
                    </el-option>
                    <el-option
                      v-for="item in projectList"
                      :key="item.projectId"
                      :label="item.projectName"
                      :value="item.projectId"
                    >
                      <span
                        style="
                          display: inline-block;
                          width: 135px;
                          color: #8492a6;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        :title="item.projectCode"
                        >{{ item.projectCode }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          margin: 0 0px 0 23px;
                          color: #8492a6;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        :title="item.projectName"
                        >{{ item.projectName }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 100px;
                          font-size: 13px;
                          margin-left: 10px;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        :title="item.projectCategoryName"
                      >
                        {{ item.projectCategoryName }}
                      </span>
                      <span
                        style="
                          display: inline-block;
                          width: 50px;
                          font-size: 13px;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        :title="item.projectTypeName"
                      >
                        {{ item.projectTypeName }}
                      </span>
                    </el-option>
                  </el-select>
                  <!-- <el-select
                    multiple
                    style="width: 268px; heigth: 100%"
                    v-model="contractForm.projectIds"
                    placeholder="请选择"
                    clearable
                    value-key="projectId"
                  >
                    <el-option
                      v-for="(item, index) in projectList"
                      :key="item.projectId"
                      :label="item.projectName"
                      :value="item"
                    />
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="选择防区：" prop="armedzonename">
                  <el-select
                    v-model="customerForm.armedzonename"
                    placeholder="请选择"
                    clearable
                    filterable
                    class="search-input"
                  >
                    <!-- @change="handleDefenseChange" -->
                    <el-option
                      v-for="dict in defenseList"
                      :key="dict.armedzoneName"
                      :label="dict.armedzoneName"
                      :value="dict.armedzoneName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="测试人员：" prop="userIds">
                  <el-select
                    v-model="customerForm.userIds"
                    placeholder="请选择"
                    clearable
                    filterable
                    class="search-input"
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                  >
                    <el-option key="0" label="" value="" disabled>
                      <span style="float: left; color: #8492a6">人员姓名</span>
                      <span style="margin: 0 80px 0 50px; color: #8492a6"
                        >联系方式</span
                      >
                      <span
                        style="
                          margin: 0 100px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >职位</span
                      >
                      <span style="color: #8492a6; font-size: 13px">部门</span>
                    </el-option>
                    <el-option
                      v-for="item in testuserList"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.userId"
                    >
                      <span
                        style="display: inline-block; width: 80px; float: left"
                        >{{ item.nickName }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          margin: 0 15px 0 23px;
                          color: #8492a6;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        >{{ item.phonenumber ? item.phonenumber : "--" }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          font-size: 13px;
                          margin: 0 0px 0 0px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.postName ? item.postName : "--" }}
                      </span>
                      <span
                        style="
                          display: inline-block;
                          margin: 0 0px 0 0px;
                          font-size: 13px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.fullDeptName ? item.fullDeptName : "--" }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="测试时间:" prop="testTime">
                  <el-date-picker
                    v-model="customerForm.testTime"
                    format="YYYY-MM-DD HH:mm:ss"
                    class="search-input"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0">
              <el-col :span="24">
                <el-form-item label="总结：" prop="summary">
                  <el-input
                    style="width: 100%"
                    v-model="customerForm.summary"
                    type="textarea"
                    maxlength="2000"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0">
              <el-col :span="6">
                <el-form-item label="产品技术文档:" label-width="110">
                  <Upload
                    :fileList="customerForm.productFlies"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    :limit="10"
                    accept=".doc,.docx,.pdf,.jpg,.png"
                    @success="(result) => uploadSuccess(result, 1)"
                    @deleteFile="(result) => uploadRemove(result, 1)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 添加联系人 -->
      <el-collapse-item
        name="2"
        style="position: relative"
        v-if="contactAddShow"
        class="transform-up"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">{{
            operateType !== "edit" ? "添加测试数据" : "编辑测试数据"
          }}</span>
        </template>
        <div class="customer-info" v-if="addtype == 1">
          <el-form
            :model="contactForm"
            ref="contactFormRef"
            :rules="queryContactRules"
            label-width="100px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="选择无人机:" prop="newdroneId">
                  <el-select
                    v-model="contactForm.newdroneId"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                    @change="selectdroneId($event)"
                  >
                    <el-option
                      v-for="dict in UAVList"
                      :key="dict.droneId"
                      :label="`${dict.droneBrand}  ${dict.droneType}`"
                      :value="`${dict.droneId}+${dict.droneBrand}+${dict.droneType}`"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="飞行频点:" prop="flyFrequencyPoint">
                  <el-select
                    v-model="contactForm.flyFrequencyPoint"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in frequencyList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="是否进入姿态模式："
                  prop="attitudeMode"
                  label-width="150"
                >
                  <el-select
                    v-model="contactForm.attitudeMode"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in statusList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="GNSS：" prop="position" label-width="120">
                  <el-input
                    v-model="contactForm.gnss"
                    placeholder="请输入"
                    clearable
                    maxlength="30"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0">
              <el-col :span="6">
                <el-form-item label="起飞位置：">
                  <!-- <el-input
                    v-model="contactForm.takeOffPosition"
                    placeholder="请输入"
                    clearable
                    maxlength="30"
                    style="width: 268px"
                  /> -->
                  <el-select
                    v-model="contactForm.takeOffPosition"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in tekeoffList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="是否成功：" prop="succeeFlag">
                  <el-select
                    v-model="contactForm.succeeFlag"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in statusList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="反制距离：" label-width="150">
                  <el-input
                    v-model="contactForm.counterDistance"
                    placeholder="请输入"
                    clearable
                    maxlength="30"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="干通比：" label-width="120">
                  <el-input
                    v-model="contactForm.ratio"
                    placeholder="请输入"
                    clearable
                    maxlength="30"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="测试环境：" prop="testEnvironment">
                  <el-select
                    v-model="contactForm.testEnvironment"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in environmentList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="customer-info" v-if="addtype == 2">
          <el-form
            :model="DetectioncontactForm"
            ref="contactFormRef"
            :rules="DetectionqueryContactRules"
            label-width="110px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="选择无人机:" prop="newdroneId">
                  <el-select
                    v-model="DetectioncontactForm.newdroneId"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                    @change="selectdroneId($event)"
                  >
                    <el-option
                      v-for="dict in UAVList"
                      :key="dict.droneId"
                      :label="`${dict.droneBrand}  ${dict.droneType}`"
                      :value="`${dict.droneId}+${dict.droneBrand}+${dict.droneType}`"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="飞行频点:" prop="flyFrequencyPoint">
                  <el-select
                    v-model="DetectioncontactForm.flyFrequencyPoint"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in frequencyList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="起飞位置：">
                  <!-- <el-input
                    v-model="DetectioncontactForm.takeOffPosition"
                    placeholder="请输入"
                    clearable
                    maxlength="30"
                    class="search-input"
                    style="width: 268px"
                  /> -->
                  <el-select
                    v-model="DetectioncontactForm.takeOffPosition"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in tekeoffList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="是否发现：" prop="succeeFlag">
                  <el-select
                    v-model="DetectioncontactForm.succeeFlag"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in statusList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0">
              <el-col :span="6">
                <el-form-item label="发现时间：" prop="discoveryTime">
                  <el-date-picker
                    v-model="DetectioncontactForm.discoveryTime"
                    format="YYYY-MM-DD HH:mm:ss"
                    class="search-input"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="发现高度:">
                  <el-input
                    v-model="DetectioncontactForm.discoveryHeight"
                    placeholder="请输入"
                    clearable
                    maxlength="30"
                    style="width: 268px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="测试环境：" prop="testEnvironment">
                  <el-select
                    v-model="DetectioncontactForm.testEnvironment"
                    placeholder="请选择"
                    clearable
                    class="search-select"
                  >
                    <el-option
                      v-for="dict in environmentList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="测试质量:">
                  <el-input
                    v-model="DetectioncontactForm.testQuality"
                    placeholder="请输入"
                    clearable
                    maxlength="30"
                    style="width: 268px"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="无人机截图:">
                  <Upload
                    :fileList="DetectioncontactForm.droneFlies"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    @success="(result) => uploadSuccess(result, 2)"
                    @deleteFile="(result) => uploadRemove(result, 2)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="平台截图:">
                  <Upload
                    :fileList="DetectioncontactForm.platformFile"
                    :isFull="true"
                    :isCanDelete="pageType == 'detail' ? false : true"
                    :disabled="pageType == 'detail'"
                    :showButton="true"
                    @success="(result) => uploadSuccess(result, 3)"
                    @deleteFile="(result) => uploadRemove(result, 3)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 测试数据列表 -->
      <el-collapse-item
        name="3"
        style="position: relative"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">测试数据列表</span>
          <div
            v-if="pageType !== 'detail' && !contactAddShow"
            class="nofixed-search-button button-position"
          >
            <el-button
              class="btn add"
              @click.stop="handleContactOperate(1)"
              style="width: 150px"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加反制测试数据</el-button
            >
            <el-button
              class="btn add"
              @click.stop="handleContactOperate(2)"
              style="width: 150px"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加侦测测试数据</el-button
            >
          </div>
          <div
            class="nofixed-search-button button-position"
            v-else
            v-if="pageType !== 'detail'"
          >
            <el-button
              class="btn add"
              @click.stop="handleContactAdd(contactFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
            <el-button class="btn direction" @click.stop="handleCustomerBack"
              ><el-icon class="icon" color="#fff"> <ArrowUp /> </el-icon
              >关闭</el-button
            >
          </div>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="testList"
            border
            :height="
              pageType === 'detail'
                ? '100%'
                : contactAddShow
                ? '380px'
                : '380px'
            "
            :header-cell-style="{ 'text-align': 'center' }"
            :row-class-name="tableRowClassName"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
              v-if="pageType !== 'detail'"
            >
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <img
                    src="@/assets/icons/images/edit.png"
                    class="table-icon"
                    title="编辑"
                    @click="handleOperate('edit', row, $index)"
                  />
                  <img
                    src="@/assets/icons/images/delete.png"
                    class="table-icon"
                    title="删除"
                    @click="handleOperate('delete', row, $index)"
                  />
                </div> </template
            ></el-table-column>
            <el-table-column
              label="序号"
              type="index"
              :show-overflow-tooltip="true"
              min-width="60"
            />
            <el-table-column
              label="无人机"
              prop="UAVshow"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row, $index }">
                {{ row.droneBrand + "  " + row.droneType }}
              </template>
            </el-table-column>
            <el-table-column
              label="飞行频点"
              prop="flyFrequencyPoint"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row, $index }">
                {{ filterflyFrequencyPoint(row) }}
              </template>
            </el-table-column>
            <el-table-column
              label="起飞位置"
              prop="takeOffPosition"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row, $index }">
                {{ filtertakeOffPosition(row) }}
              </template>
            </el-table-column>
            <el-table-column
              label="是否成功/发现"
              prop="succeeFlag"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row, $index }">
                {{ row.succeeFlag == 1 ? "是" : "否" }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import {
  getProvinceApi,
  addCustomerApi,
  editCustomerApi,
} from "@/api/information/customer";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import Upload from "@/components/Upload/index";
import {
  getflymodifyApi,
  getProjectPassListApi,
  getArmedzoneInfoVoListApi,
  getpersonnelApi,
  getproductdetailApi,
} from "@/api/operation/flightdata.js";
import { getUserListApi } from "@/api/operation/work";
import { getproductEstimateListApi } from "@/api/operation/productLibrary.js";
const emit = defineEmits([
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
  FormTemplate: {
    type: Object,
    default: {
      droneFlies: [],
      platformFile: [],
    },
  },
});

// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const customerFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("add");
// 新增测试数据表单显隐
const contactAddShow = ref(false);
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 下拉框引用
const refSelect = ref();
//联系人模块标题文字
const contacts = ref("添加联系人");
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 项目列表
const projectList = ref([]);
//飞行类型下拉
let flightTypeList = ref([]);
//防区下拉
let defenseList = ref([]);
//测试人员下拉
let testuserList = ref([]);
//无人机列表
let UAVList = ref([]);
//飞行频点
let frequencyList = ref([]);
//测试环境
let environmentList = ref([]);
//是否状态
let statusList = ref([]);
//列表测试数据
let testList = ref([]);
//起飞位置下拉
let tekeoffList = ref([]);
//省市区校验规则
const provinceValidate = (rule, value, callback) => {
  const { provinceId, cityId, zoneId } = customerForm.value;
  if (!provinceId || !cityId || !zoneId) {
    callback(new Error("请选择省市区"));
  } else {
    callback();
  }
};

// 客户表单数据模板
const customerFormTemplate = {
  productFlies: [],
  userIds: [],
};
// 联系人表单数据模板
const contactFormTemplate = {};
const DetectioncontactFormTemplate = {
  droneFlies: [],
  platformFile: [],
};
const data = reactive({
  // 客户表单
  customerForm: JSON.parse(JSON.stringify(customerFormTemplate)),
  // 反制表单
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  //侦测表单
  DetectioncontactForm: JSON.parse(
    JSON.stringify(DetectioncontactFormTemplate)
  ),
  // 客户表单校验规则
  queryRules: {
    // deptId: [{ required: true, message: "请选择业务部门", trigger: "change" }],
    flyType: [{ required: true, message: "请选择飞行类型", trigger: "change" }],
    testTime: [
      { required: true, message: "请选择测试时间", trigger: "change" },
    ],
    userIds: [
      { required: true, message: "请选择测试人员", trigger: "change" },
    ],
    cityId: [
      {
        required: true,
        validator: provinceValidate,
        message: "请选择省市区",
        trigger: "change",
      },
    ],
  },
  // 联系人表单校验规则
  queryContactRules: {
    newdroneId: [
      { required: true, message: "请选择无人机", trigger: "change" },
    ],
    flyFrequencyPoint: [
      { required: true, message: "请选择飞行频点", trigger: "change" },
    ],
    attitudeMode: [
      { required: true, message: "请选择是否进入姿态模式", trigger: "change" },
    ],
    succeeFlag: [
      { required: true, message: "请选择是否成功", trigger: "change" },
    ],
    testEnvironment: [
      { required: true, message: "请选择测试环境", trigger: "change" },
    ],
  },
  // 联系人表单校验规则
  DetectionqueryContactRules: {
    newdroneId: [
      { required: true, message: "请选择无人机", trigger: "change" },
    ],
    flyFrequencyPoint: [
      { required: true, message: "请选择飞行频点", trigger: "change" },
    ],
    testEnvironment: [
      { required: true, message: "请选择飞行频点", trigger: "change" },
    ],
    succeeFlag: [
      { required: true, message: "请选择是否发现", trigger: "change" },
    ],
    testEnvironment: [
      { required: true, message: "请选择测试环境", trigger: "change" },
    ],
  },
  // 省列表
  provinceList: [],
  // 市列表
  cityList: [],
  // 区列表
  areaList: [],
});

const {
  customerForm,
  contactForm,
  queryRules,
  queryContactRules,
  DetectionqueryContactRules,
  DetectioncontactForm,
  provinceList,
  cityList,
  areaList,
} = toRefs(data);

watch(
  () => props.FormTemplate,
  async (newValue, oldValue) => {
    if (!newValue.productFlies) {
      newValue.productFlies = [];
    }
    // newValue.tester = newValue.testers.map(Number);
    customerForm.value = JSON.parse(JSON.stringify(newValue));

    await getProvinceApi(customerForm.value.provinceId).then((res) => {
      if (res.code === 200) {
        cityList.value = res.data;
      }
    });
    await getProvinceApi(customerForm.value.cityId).then((res) => {
      if (res.code === 200) {
        areaList.value = res.data;
      }
    });
    customerForm.value.testData.map((item, index) => {
      item.UAVshow = item.droneBrand + "  " + item.droneType;
    });
    testList.value = customerForm.value.testData;
  },
  { deep: true }
);

/**
 * @description: 更具status来隐藏某条数据
 */
const tableRowClassName = ({ row, index }) => {
  if (row.status == 1) {
    return "hidden-row";
  }
  return "";
};

/**
 * @description: 更具status来隐藏某条数据
 */
const filterflyFrequencyPoint = (row) => {
  let str = "";
  frequencyList.value.forEach((item) => {
    if (row.flyFrequencyPoint == item.value) {
      str = item.label;
    }
  });
  return str;
};

/**
 * @description: 更具status来隐藏某条数据
 */
const filtertakeOffPosition = (row) => {
  let str = "";
  tekeoffList.value.forEach((item) => {
    if (row.takeOffPosition == item.value) {
      str = item.label;
    }
  });
  return str;
};

/**
 * @description: 选择无人机
 */
const selectdroneId = (event) => {
  if (addtype.value == 1) {
    contactForm.value.droneBrand = event.split("+")[1];
    contactForm.value.droneType = event.split("+")[2];
    contactForm.value.droneId = event.split("+")[0];
  } else {
    DetectioncontactForm.value.droneBrand = event.split("+")[1];
    DetectioncontactForm.value.droneType = event.split("+")[2];
    DetectioncontactForm.value.droneId = event.split("+")[0];
  }
};
/**
 * @description: 保存
 * @param {Object} customerFormRef 客户表单引用
 */
const handleAddSave = async (customerFormRef, type = "") => {
  if (!customerFormRef) return;
  if (testList.value.length == 0) {
    ElMessage.error("请添加测试数据");
    return;
  }
  await customerFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        `确定${props.pageType === "add" ? "保存" : "删除"}以上数据吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          confirmButtonClass: "confirmBtnClass",
          cancelButtonClass: "cancelBtnClass",
        }
      )
        .then(async () => {
          let res;
          let counters = testList.value.filter((item, index) => {
            return item.deviceType == 0;
          });
          let surveillances = testList.value.filter((item, index) => {
            return item.deviceType == 1;
          });
          // customerForm.value.tester = customerForm.value.tester.join(",");
          if (props.pageType == "add" || props.pageType == "edit") {
            customerForm.value.status = 0;
          }
          if (type == "delete") {
            customerForm.value.status = 1;
          }
          let obj = {
            ...customerForm.value,
            counters,
            surveillances,
          };
          res = await getflymodifyApi(obj);
          if (res.code === 200) {
            emit("update:flightdataAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            customerForm.value = JSON.parse(
              JSON.stringify(customerFormTemplate)
            );
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("update:flightdataAddShow", false);
    customerForm.value = JSON.parse(JSON.stringify(customerFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:flightdataAddShow", false);
        customerForm.value = JSON.parse(JSON.stringify(customerFormTemplate));
        contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
        DetectioncontactForm.value = JSON.parse(
          JSON.stringify(DetectioncontactFormTemplate)
        );
        testList.value = [];
        addtype.value = 0;
        if (customerFormRef.value) {
          customerFormRef.value.resetFields();
        }
        contactAddShow.value = false;
      })
      .catch(() => {});
  }
};

/**
 * @description: 新增、编辑测试数据
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid) => {
    if (valid) {
      if (operateType.value === "edit") {
        operateType.value = "add";
        if (addtype.value == 1) {
          testList.value[tableIndex.value] = JSON.parse(
            JSON.stringify(contactForm.value)
          );
        } else if (addtype.value == 2) {
          testList.value[tableIndex.value] = JSON.parse(
            JSON.stringify(DetectioncontactForm.value)
          );
        }
      } else {
        if (addtype.value == 1) {
          contactForm.value.deviceType = addtype.value - 1;
          //添加的状态 0
          contactForm.value.status = 0;
          testList.value.push(JSON.parse(JSON.stringify(contactForm.value)));
        } else {
          DetectioncontactForm.value.deviceType = addtype.value - 1;
          DetectioncontactForm.value.status = 0;
          testList.value.push(
            JSON.parse(JSON.stringify(DetectioncontactForm.value))
          );
        }
      }
      contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
      DetectioncontactForm.value = JSON.parse(
        JSON.stringify(DetectioncontactFormTemplate)
      );
      nextTick(() => {
        refInput.value.focus();
      });
      contactFormRef.resetFields();
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response, type) {
  switch (type) {
    case 1:
      customerForm.value.productFlies.push({ ...response });
      break;
    case 2:
      DetectioncontactForm.value.droneFlies.push({ ...response });
      break;
    case 3:
      DetectioncontactForm.value.platformFile.push({ ...response });

      break;
    default:
      break;
  }
}
/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index, type) {
  switch (type) {
    case 1:
      customerForm.value.productFlies.splice(index, 1);
      break;
    case 2:
      DetectioncontactForm.value.droneFlies.splice(index, 1);
      break;
    case 3:
      DetectioncontactForm.value.platformFile.splice(index, 1);
      break;
    default:
      break;
  }
}

/**
 * @description: 处理编辑信息
 * @param {Number} id
 */
const handleEditInfo = async (id, type) => {
  try {
    detailInfoShow.value = true;
    let res = await getproductdetailApi(id);
    if (res.code == 200) {
      if (!res.data.productFlies) {
        res.data.productFlies = [];
      }
      // res.data.tester = res.data.testers.map(Number);
      customerForm.value = JSON.parse(JSON.stringify(res.data));
      await getProvinceApi(customerForm.value.provinceId).then((res) => {
        if (res.code === 200) {
          cityList.value = res.data;
        }
      });
      await getProvinceApi(customerForm.value.cityId).then((res) => {
        if (res.code === 200) {
          areaList.value = res.data;
        }
      });
      customerForm.value.testData.map((item, index) => {
        item.UAVshow = item.droneBrand + "  " + item.droneType;
      });
      testList.value = customerForm.value.testData;
      if (type == "delete") {
        handleAddSave(customerFormRef.value, "delete");
      }
    }
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};
/**
 * @description: 处理联系人操作
 */
let addtype = ref(0);
const handleContactOperate = (type) => {
  contactAddShow.value = true;
  operateType.value = "add";
  addtype.value = type;
  contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
  DetectioncontactForm.value = JSON.parse(
    JSON.stringify(DetectioncontactFormTemplate)
  );
  nextTick(() => {
    refInput.value.focus();
  });
};

/**
 * @description: 联系人返回
 */
const handleCustomerBack = () => {
  contactAddShow.value = false;
  nextTick(() => {
    refSelect.value.focus();
  });
};

/**
 * @description: 处理省市区操作
 * @param {String} type 类型
 */
const handleProvince = (type) => {
  switch (type) {
    case "province":
      cityList.value = [];
      areaList.value = [];
      customerForm.value.cityId = null;
      customerForm.value.zoneId = null;
      getProvinceApi(customerForm.value.provinceId).then((res) => {
        if (res.code === 200) {
          cityList.value = res.data;
        }
      });
      break;
    case "city":
      areaList.value = [];
      customerForm.value.zoneId = null;
      getProvinceApi(customerForm.value.cityId).then((res) => {
        if (res.code === 200) {
          areaList.value = res.data;
        }
      });
      break;
  }
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    if (contactFormRef.value) {
      contactFormRef.value.resetFields();
    }
    tableIndex.value = tabIndex;
    addtype.value = row.deviceType + 1;
    if (row.deviceType == 0) {
      contactForm.value = JSON.parse(JSON.stringify(row));
      contactForm.value.newdroneId = `${row.droneId}+${row.droneBrand}+${row.droneType}`;
    } else if (row.deviceType == 1) {
      DetectioncontactForm.value = JSON.parse(JSON.stringify(row));
      DetectioncontactForm.value.newdroneId = `${row.droneId}+${row.droneBrand}+${row.droneType}`;
    }

    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refInput.value.focus(); // 聚焦
    });
  } else {
    ElMessageBox.confirm("此操作将删除该测试数据，是否继续？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
      type: "warning",
    })
      .then(async () => {
        // testList.value.splice(tabIndex, 1);
        testList.value[tabIndex].status = 1;
      })
      .catch(() => {});
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  //飞行类型下拉
  await getDictsApi("fly_type").then((res) => {
    if (res.code === 200) {
      flightTypeList.value = res.data;
    }
  });

  //项目下拉
  // await getProjectPassListApi({ pageNum: 1, pageSize: 50 }).then((res) => {
  //   if (res.code === 200) {
  //     projectList.value = res.rows;
  //   }
  // });
  //防区下拉
  await getArmedzoneInfoVoListApi().then((res) => {
    defenseList.value = res;
  });
  //测试人员下拉
  await getUserListApi(2).then((res) => {
    console.log("测试人员下拉");
    console.log(res);
    testuserList.value = res;
  });
  //无人机列表
  await getproductEstimateListApi({}, { pageNum: 1, pageSize: 50 }).then(
    (res) => {
      if (res.code === 200) {
        UAVList.value = res.rows;
      }
    }
  );
  //飞行频点下拉
  await getDictsApi("fly_frequency_point").then((res) => {
    if (res.code === 200) {
      frequencyList.value = res.data;
    }
  });

  //测试环境下拉
  await getDictsApi("test_environment").then((res) => {
    if (res.code === 200) {
      environmentList.value = res.data;
    }
  });
  //飞行类型下拉
  await getDictsApi("take_off_position").then((res) => {
    if (res.code === 200) {
      tekeoffList.value = res.data;
    }
  });
  await getDictsApi("erp_warehousing").then((res) => {
    // 审核状态
    if (res.code === 200) {
      statusList.value = res.data;
    }
  });

  // 省列表
  await getProvinceApi(1).then((res) => {
    if (res.code === 200) {
      provinceList.value = res.data;
    }
  });
}

onMounted(() => {
  getDicts();
  if (props.pageType === "add") {
    nextTick(() => {
      refSelect.value.focus();
    });
  }
});

defineExpose({
  handleEditInfo,
});
</script>
<style lang="scss" scoped>
.customerAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .customer-info {
    padding: 20px 10px 5px 10px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
  :deep(.el-date-editor.el-input) {
    width: 91% !important;
  }
  ::v-deep .el-table .hidden-row {
    display: none !important;
  }
  :deep(.el-form-item--default) {
  margin-bottom: 22px;
}
:deep(.el-form-item--default .el-form-item__error) {
  padding-top: 5px;
}
}
</style>
